{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python 的数据类型\n",
    "\n",
    "- 六个标准的数据类型\n",
    "\n",
    "1. Number (数字)\n",
    "    \n",
    "    - int\n",
    "\n",
    "    - bool\n",
    "\n",
    "    - float\n",
    "\n",
    "    - complex （复数）\n",
    "    \n",
    "2. String （字符串）\n",
    "\n",
    "3. List （列表）\n",
    "\n",
    "4. Tuple （元组）\n",
    "\n",
    "5. Sets\n",
    "\n",
    "6. Dictionary\n",
    "\n",
    "- `type()` 可以用于查询变量的数据类型\n",
    "\n",
    "- `isinstance(var, type)` 用于判断数据类型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Number"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "int"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# int\n",
    "a = 1 \n",
    "type(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(bool, bool)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = True\n",
    "b = False \n",
    "type(a), type(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "float"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 1.345\n",
    "type(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "complex"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 1+1j\n",
    "type(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "isinstance(a, complex)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 二、八、十、十六进制\n",
    "\n",
    "- 二进制  bin(8)\n",
    "\n",
    "- 八进制： 逢8进1\n",
    "\n",
    "    - oct(8)  转换成8进制\n",
    "\n",
    "- 16进制：\n",
    "    - hex(16)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0b1010'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bin(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0o144'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "oct(100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'0x10'"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "hex(16)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 字符串\n",
    "\n",
    "- 字符串：单引号,双引号,包括三引号包围的字符组\n",
    "  - 三个引号包围可以定义多行字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'str'>\n",
      "it's me\n"
     ]
    }
   ],
   "source": [
    "a='110'\n",
    "print(type(a))\n",
    "a= \"it's me\"\n",
    "print(a)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 使用反斜杠（\\）可以转义特殊字符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hey hey \n",
      " hi hi\n",
      "----------\n",
      "hey hey \\n hi hi\n",
      "----------\n",
      "it's me\n"
     ]
    }
   ],
   "source": [
    "#\\n换行\n",
    "a = 'hey hey \\n hi hi'\n",
    "print(a)\n",
    "print('-'*10)\n",
    "a ='hey hey \\\\n hi hi'\n",
    "print(a)\n",
    "print('-'*10)\n",
    "a = 'it\\'s me'\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 前面加r,可以屏蔽转义符和特殊字符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hey hey \\\\n hi hi\n",
      "jijij\\'jijijij\n"
     ]
    }
   ],
   "source": [
    "#前面加r,可以屏蔽转义符和特殊字符，是什么样就显示什么样子\n",
    "a =r'hey hey \\\\n hi hi'\n",
    "print(a)\n",
    "a = r'jijij\\'jijijij'\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 下标和切片"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 下标\n",
    "  - 字符串，元组，列表都会用到**下标**的概念。在字符串中，**下标**指的是每一个字符的位置。\n",
    "  - 在python中，位置编号从左至右是从0位开始，依次递增；从右至左是从-1开始，依次递减（-1，-2，-3，...）\n",
    "  - 通过下标，我们可以提取字符串中的元素\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "g\n",
      "a\n"
     ]
    }
   ],
   "source": [
    "a = 'good day'\n",
    "print(a[0])  #使用`str[位置]`提取元素\n",
    "print(a[-2])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 切片\n",
    "    \n",
    "- 切片：截取一段元素或一部分。\n",
    "  - 字符串、列表、元组都支持切片操作。\n",
    "- 切片的语法: `[start_position:end_position:step]`\n",
    "  - python中，切片的方式是「**取头不取尾**」，即end_position位置的元素不会被选取。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abcd\n",
      "abcd\n",
      "bcdefg\n",
      "aceg\n",
      "gfedcba\n",
      "gfed\n",
      "fedc\n"
     ]
    }
   ],
   "source": [
    "#切片：索引从0开始，-1 从末尾开始; 通过位置获得元素\n",
    "a = 'abcdefg'\n",
    "print(a[0:4])  # 结果：'abcd'\n",
    "print(a[:4])  # 如果省略 start_position, 则从头开始取\n",
    "print(a[1:])  # 如果省略 end_position, 则会取到最后一位\n",
    "print(a[::2])   # 间隔1位获取数据\n",
    "print(a[-1::-1])   # 步长为-1：倒着取\n",
    "# print(a[::-1])\n",
    "print(a[-1:2:-1])\n",
    "print(a[5:1:-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字符串的常见操作\n",
    "\n",
    "- 增删改查"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 增\n",
    "\n",
    "##### `+`，`*`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "helloworld\n",
      "heyheyheyheyheyheyheyheyheyhey\n"
     ]
    }
   ],
   "source": [
    "# 用 + 可以连接字符串； 用*可以重复字符串\n",
    "a = 'hello'\n",
    "b = 'world'\n",
    "c=a+b\n",
    "print(c)\n",
    "c = 'hey'*10\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### join\n",
    "- 拼接字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mayaprilkate\n",
      "mayandaprilandkate\n",
      "may_april_kate\n"
     ]
    }
   ],
   "source": [
    "b = ['may','april','kate']\n",
    "print(''.join(b))\n",
    "print('and'.join(b))\n",
    "print('_'.join(b))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 删\n",
    "\n",
    "- `str.strip()`：删除字符串两端的空白字符\n",
    "- `str.lstrip()`：删除字符串左侧的空白字符\n",
    "- `str.rstrip()`：删除字符串右侧的空白字符\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "good day 8\n",
      "good day   10\n",
      "  good day 10\n"
     ]
    }
   ],
   "source": [
    "a = '  good day  '\n",
    "print(a.strip(), len(a.strip()))\n",
    "print(a.lstrip(), len(a.lstrip()))\n",
    "print(a.rstrip(), len(a.rstrip()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "20"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "price = '$20'\n",
    "print(price.lstrip('$'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 改\n",
    "\n",
    "```{attention}\n",
    "字符串不能通过位置做修改\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### replace\n",
    "- `str.replace(str_old,str_new,count)`   #如果count指定，则替换次数不超过count次"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "goodday\n",
      "goodday\n"
     ]
    }
   ],
   "source": [
    "a = '  good day  '\n",
    "a2 = a.strip()\n",
    "print(a2.replace(' ',''))\n",
    "print(a.strip().replace(' ',''))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "wey, have a good day~ have a good day~\n",
      "wey, wave a good day~ have a good day~\n",
      "wey, wave a good day~ wave a good day~\n"
     ]
    }
   ],
   "source": [
    "a = 'hey, have a good day~ have a good day~'\n",
    "print(a.replace('h','w',1))\n",
    "print(a.replace('h','w',2))\n",
    "print(a.replace('h','w',3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### split\n",
    "- `str.split(\"-\",maxsplit)\n",
    "- 以'-'为分隔符切片str，如果maxsplit有指定值，则仅分隔 maxsplit 个子字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2022'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "date = '2022-03-09'\n",
    "date.split('-')[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### capitalize\n",
    "- `str.capitalize()`: 把str的第一个字符大写\n",
    "\n",
    "##### title\n",
    "- `str.title()`: 把str中的每个单词的首字母大写\n",
    "\n",
    "##### lower\n",
    "- `str.lower()`: 都转换为小写\n",
    "\n",
    "##### upper\n",
    "- `str.upper()`: 都转换为大写\n",
    "\n",
    "##### ljust\n",
    "- `str.ljust(width)`: 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串\n",
    "\n",
    "##### rjust\n",
    "- `str.rjust(width)`: 返回一个原字符串右对齐,并使用空格填充至长度 width的新字符串\n",
    "\n",
    "##### center\n",
    "- `str.center(width)`: 返回一个原字符串居中,并使用空格填充至长度 width 的新字符串\n",
    "\n",
    "##### partition\n",
    "- `str.partition(sep)`: 把str以sep分割成三部分,str2前，str2和str2后 (返回一个三元元组(head,sep,tail))\n",
    "\n",
    "##### rpartition\n",
    "- `str.rpartition(sep)`: 类似于 partition()函数,只是从右边开始\n",
    "\n",
    "##### splitlines\n",
    "\n",
    "- `str.splitlines()`: 按照行分隔，返回一个包含各行作为元素的列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                  nice day day\n",
      "('nice ', 'd', 'ay day')\n",
      "('nice day ', 'd', 'ay')\n",
      "['hey', 'have', 'have a nice day', 'have a good day']\n"
     ]
    }
   ],
   "source": [
    "a = 'nice day day'\n",
    "print(a.rjust(30))\n",
    "print(a.partition('d'))\n",
    "print(a.rpartition('d'))\n",
    "\n",
    "a = '''hey\n",
    "have\n",
    "have a nice day\n",
    "have a good day\n",
    "'''\n",
    "print(a.splitlines())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 查\n",
    "\n",
    "##### find \n",
    "`str.find(str1, start = 0, end= len(str))`: 检测 str1 是否包含在`str[start:end]`中，如果是返回第一个出现的索引值，否则返回 -1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "'str' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_19568/876064568.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'hey you you!'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mfind\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'y'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'm'\u001b[0m \u001b[1;31m#不能通过位置做修改\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      4\u001b[0m \u001b[1;31m# print(a)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: 'str' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "a = 'hey you you!'\n",
    "print(a.find('y'))\n",
    "a[0] = 'm' #不能通过位置做修改\n",
    "# print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### `rfind`\n",
    "- 类似于 find()函数，不过是从右边开始查找"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 'heyheyhey'\n",
    "a.rfind('h')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### index\n",
    "- 和`find`方法一样，只不过如果str1不在str中会报一个异常"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "substring not found",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_19568/3775140893.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0ma\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'hey you you!'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'm'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: substring not found"
     ]
    }
   ],
   "source": [
    "a = 'hey you you!'\n",
    "a.index('m')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### `rindex`\n",
    "- 类似于 index()，不过是从右边开始"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### `count`\n",
    "\n",
    "- `str.count('str1',start=1, end=len(str))`: 返回str1在`str[start:end]`之间出现的次数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "a = 'heyheyhey'\n",
    "print(a.count('h',0,3))\n",
    "print(a.count('hey'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#最大，max(str) ; 最小，min(str)\n",
    "\n",
    "str1 = 'ABCabc'\n",
    "min(str1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### `startswith`\n",
    "- `str.startswith('hey')`: 检查字符串是否是以'hey'开头, 是则返回 True，否则返回 False\n",
    "\n",
    "##### `endswith`\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##  列表\n",
    "\n",
    "- 用于存放一组值, 用 [ ] 定义列表，值用` ，`隔开\n",
    "- 是一种有序的集合，可以添加、删除和修改其中的元素\n",
    "- 列表中的元素可以是不同的类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2.8, 'abc', [3, 2]]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# define a list\n",
    "a = [1,2.8,'abc',[3,2]]\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 列表的常见操作"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 长度（包含几个元素）\n",
    "- `len(str)`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = [1,2,'hey',5]\n",
    "len(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 选取元素\n",
    "- `ls[pos]`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,'hey',5]\n",
    "print(a[1])\n",
    "print(a[-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 切片 （slice）\n",
    "\n",
    "- 根据下标的范围获取一部分数据，同字符串操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2.8, 'abc', [3, 2]]\n",
      "[[3, 2], 'abc', 2.8, 1]\n",
      "[[3, 2]]\n"
     ]
    }
   ],
   "source": [
    "#slice\n",
    "a = [1, 2.8, 'abc', [3, 2]]\n",
    "print(a)\n",
    "print(a[-1::-1])  # 倒着取需要后面加上倒取的步长(:-1)\n",
    "print(a[-1:2:-1])  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[3, 2], 'abc', 2.8, 1]"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.reverse()\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 修改\n",
    "- 要通过下标/位置来确定要修改的是哪个元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[200, 2.8, 'abc', [3, 2]]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 修改list中的值\n",
    "a = [1, 2.8, 'abc', [3, 2]]\n",
    "a[0]=200\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 添加元素\n",
    "\n",
    "- `+`, `*`\n",
    "- `append`, `extend`, `insert`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2.8, 'abc', [3, 2]]\n",
      "[1, 2.8, 'abc', [3, 2], 1, 2, 3]\n"
     ]
    }
   ],
   "source": [
    "# list + list \n",
    "a = [1, 2.8, 'abc', [3, 2]]\n",
    "print(a)\n",
    "b=[1,2,3]\n",
    "c = a+b\n",
    "print(c)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2.8, 'abc', [3, 2], 1, 2.8, 'abc', [3, 2], 1, 2.8, 'abc', [3, 2], 1, 2.8, 'abc', [3, 2]]\n"
     ]
    }
   ],
   "source": [
    "# list*num\n",
    "a = [1, 2.8, 'abc', [3, 2]]\n",
    "c = a*4\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### `append`\n",
    "- 在列表后面添加一个元素。NOTE：takes exactly one argument"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, [10, 20, 30]]\n",
      "[1, 2, 3, [10, 20, 30], 10, 20, 30]\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "a.append([10,20,30])\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### `extend`\n",
    "- `list.extend(ls2)`: 将ls2中的元素逐一添加到list中"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 10, 20, 30]\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "a.extend([10,20,30])\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### `insert`\n",
    "- `list.insert(position,var)`: 在指定位置`position`前插入元素`var `"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 3, 2, 3]"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "a.insert(1,3)\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 查找元素\n",
    "\n",
    "##### in, not in\n",
    "\n",
    "- `in`（存在），如果存在那么结果为true，否则为false (字符串也可以使用)\n",
    "- `not in`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3,4,5]\n",
    "print('10' not in a)\n",
    "print('10' in a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### `index`, `count`\n",
    "- 和字符串中的用法相同"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "a = [10,20,30,50,20,'hey']\n",
    "# list.count(var)  计算var出现的次数\n",
    "print(a.count(10))\n",
    "print(a.index('hey'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 删除元素\n",
    "\n",
    "- del: 根据下标删除, `del list[pos]`\n",
    "- pop: 弹出指定位置的元素\n",
    "- remove: 根据元素值删除\n",
    "- clear: 删除列表中所有元素"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "[2, 3, 4, 5]\n",
      "----------\n",
      "del\n",
      "[2, 4, 5]\n",
      "----------\n",
      "remove\n",
      "[2, 4]\n",
      "----------\n",
      "clear\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# list.pop(index)  弹出index对应的数值\n",
    "a = [1,2,3,4,5]\n",
    "b=a.pop(0)  # 没有指定，则弹出最后一个\n",
    "print(b)\n",
    "print(a)\n",
    "print('-'*10)\n",
    "print('del')\n",
    "del a[1]\n",
    "print(a)\n",
    "print('-'*10)\n",
    "print('remove')\n",
    "a.remove(5)\n",
    "print(a)\n",
    "print('-'*10)\n",
    "print('clear')\n",
    "a.clear()\n",
    "a\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 排序\n",
    "\n",
    "##### sort\n",
    "\n",
    "- 将list按特定顺序重新排列，默认为由小到大，参数reverse=True可改为倒序，由大到小"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 4, 7, 20]\n",
      "[20, 7, 4, 2, 1]\n"
     ]
    }
   ],
   "source": [
    "# list.sort()\n",
    "a=[1,20,4,7,2]\n",
    "a.sort()  #默认升序排列\n",
    "            #? ascending=False 不能用，这里用reverse=True\n",
    "print(a)\n",
    "# 降序\n",
    "a.sort(reverse = True)\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### reverse\n",
    "\n",
    "- list.reverse(): 前后颠倒"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 复制列表"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 4, 7, 20]\n",
      "[1, 2, 4, 7, 20]\n",
      "[1, 2, 4, 7, 20]\n",
      "----------\n",
      "判断值是否相同\n",
      "True True\n",
      "check 一下内存地址\n",
      "True False\n"
     ]
    }
   ],
   "source": [
    "# 比较 list.copy() 和 = \n",
    "a = [1, 2, 4, 7, 20]\n",
    "print(a)\n",
    "b = a\n",
    "c = a.copy()\n",
    "print(b)\n",
    "print(c)\n",
    "\n",
    "print('-'*10)\n",
    "print('判断值是否相同')\n",
    "print(a==b, a==c)   # 相同\n",
    "print('check 一下内存地址')\n",
    "#id() 查看内存地址\n",
    "print(id(a) == id(b), id(a) == id(c))   # 或者使用 a is b判断地址是否相同\n",
    "# a,b指向同一个位置，a,c指向不同的位置\n",
    "# ‘=’ 相当于给a代表的数据起了另一个名字"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 4, 7, 20, 3]\n",
      "[1, 2, 4, 7, 20, 3]\n",
      "[1, 2, 4, 7, 20]\n"
     ]
    }
   ],
   "source": [
    "# b变化a也会跟着变，因为指向的内置相同\n",
    "b.append(3)\n",
    "print(b)\n",
    "print(a)\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# b = [20,30]  # 如果b重新赋值，会新划出一个内存地址\n",
    "# id(b) == id(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "df = pd.DataFrame({'name':[1,2,3],'age':[10,20,30]})\n",
    "df2 = df  # 慎用 = 复制变量\n",
    "df2 is df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### str转list\n",
    "\n",
    "- `list(str)`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a', 'b', 'c', 'd', 'e']"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# list(str)， 将字符串转成列表\n",
    "a='abcde'\n",
    "list(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tuple\n",
    "\n",
    "- 和List类似，可以存放多个值且不同类型\n",
    "  \n",
    "- 是有序的对象结合\n",
    "\n",
    "- 用() 定义\n",
    "\n",
    "- 里面的值不可修改，其它操作同List\n",
    "  - 因为tuple不可变，所以代码更安全。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tuple"
      ]
     },
     "execution_count": 71,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# define a tuple\n",
    "a=(1,2,3)\n",
    "type(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-90-5d4838213afb>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;31m# tuple 里的值不可修改\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "# tuple 里的值不可修改\n",
    "a[0]=10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 2, 3, 4, 5, 6)\n",
      "(1, 2, 3, 1, 2, 3, 1, 2, 3)\n"
     ]
    }
   ],
   "source": [
    "# tuple + tuple \n",
    "b=(4,5,6)\n",
    "print(a+b)\n",
    "print(a*3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'tuple'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(1,)"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# if tuple only have one element, we need to add comma after the first element\n",
    "a=(1,)  # 定义一个只有1个元素的tuple\n",
    "print(type(a))\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, 2, 3, ['hey', 6], 8)"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# “可变的”tuple\n",
    "a = (1,2,3,[5,6],8)\n",
    "a[3][0] = 'hey'\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Set\n",
    "\n",
    "- **无序不重复**元素的序列\n",
    "  - 不可用位置和切片取其中的元素\n",
    "\n",
    "- 基本功能是**进行成员关系测试和删除重复元素**\n",
    "\n",
    "- 可以使用{} 或 set(list/tuple/str) 定义\n",
    "\n",
    "- **集合之间的运算**： - 差集； & 交集; | 并集；^反交集(返回集合中不重复的元素;并-交)\n",
    "\n",
    "- 列表，元组， 集合三者之间可以相互转换\n",
    "\n",
    "\n",
    "\n",
    "```{note}\n",
    "创建一个空集合必须用set() 而不是{}。 {}用于定义字典\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'set'>\n",
      "{1, 2, 3}\n"
     ]
    }
   ],
   "source": [
    "#define a set: {}\n",
    "a={1,2,3}\n",
    "print(type(a))\n",
    "print(a)\n",
    "#set will drop duplicates\n",
    "a={1,1,1,2,3}\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({1}, {2, 3}, {1, 2, 3, 8}, {1, 8})"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a={1,2,3}\n",
    "b = {2,3,8}\n",
    "a-b, a&b, a|b, a^b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 增加元素\n",
    "\n",
    "- add: 增加一个值\n",
    "\n",
    "- update: 增加多个值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{1, 'jij', 'jijij'}"
      ]
     },
     "execution_count": 82,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#加入1个值， set.add()\n",
    "a.add('jijij')\n",
    "a\n",
    "# 加入多个值，set.update([])\n",
    "a.update([1,2,3])\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 删除\n",
    "\n",
    "#### `remove`\n",
    "  - `set.remove(var)`: 删除不存在的值会报错\n",
    "\n",
    "#### `discard`\n",
    "    - 删除不存在的值不会报错"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3}\n"
     ]
    },
    {
     "ename": "KeyError",
     "evalue": "4",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_19568/2426393786.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0ma\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdiscard\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mremove\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mKeyError\u001b[0m: 4"
     ]
    }
   ],
   "source": [
    "a = {1,2,3}\n",
    "a.discard(4)\n",
    "print(a)\n",
    "a.remove(4)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dictionary\n",
    "\n",
    "- 是python 中一个非常有用的内置数据类型, 可以存储任意类型对象\n",
    "\n",
    "- 用{}或dict()取定义\n",
    "  - `dt = {'key':value1, 'key2':value2}`\n",
    "  - `dt = dict(key = 1, key2=2)`\n",
    "  - `dt = {}` or `dt=dict()`\n",
    "\n",
    "- **无序的对象集合**，通过 键(key) 来存取数据\n",
    "\n",
    "  - 一种映射类型，是一个无序的 key:value 对的集合\n",
    "  \n",
    "  - **key必须使用不可变类型，在同一个字典中，key必须是惟一的**\n",
    "    - 多次对一个key放入value，后面的值会把前面的值冲掉"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': ['june', 'may', 'april'], 'age': [21, 22, 33], 'sex': 'female', 'phone': '1234'}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "dict"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#define a dictionary \n",
    "#{'key1':'str','key2':num}\n",
    "#dict(key1='str',key2=num)\n",
    "\n",
    "a = {'name':['june','may','april'],'age':[21,22,33],'sex':'female','phone':'1234'}\n",
    "print(a)\n",
    "type(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'may', 'age': 20, 'sex': 'male', 'phone': '4321'}"
      ]
     },
     "execution_count": 127,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "b = dict(name='may',age=20,sex='male',phone='4321')\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 字典的常见操作"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 改\n",
    "\n",
    "- 字典的每个元素中的数据是可以修改的，只要通过key找到，便可修改"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': '小王', 'age': [21, 22, 33], 'sex': 'female', 'phone': '1234'}\n"
     ]
    }
   ],
   "source": [
    "a = {'name':['june','may','april'],'age':[21,22,33],'sex':'female','phone':'1234'}\n",
    "a['name'] = '小王'\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 添加\n",
    "\n",
    "`df['key'] = var`: 只要键不存在，就会添加"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': '小王',\n",
       " 'age': [21, 22, 33],\n",
       " 'sex': 'female',\n",
       " 'phone': '1234',\n",
       " 'email': 'may13@cupl.edu.cn'}"
      ]
     },
     "execution_count": 86,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# add key\n",
    "a['email']='may13@cupl.edu.cn'\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'m0': 'm1234', 'm1': 'm11234'}"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a={}\n",
    "a['m0']='m1234'\n",
    "a['m1']='m11234'\n",
    "a"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 修改添加多个key\n",
    "\n",
    "- `update`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': '小王', 'age': 40, 'sex': 'female', 'phone': '1234', 'email': 'may13@cupl.edu.cn', 'stu_id': '321'}\n"
     ]
    }
   ],
   "source": [
    "# 修改或添加多个 key:value\n",
    "# a.update({'age':4, 'phone':123}) # 有则修改，无则添加\n",
    "a.update({'age':40,'stu_id':'321'})\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 删除\n",
    "\n",
    "- `del`\n",
    "- `clear`\n",
    "- `pop`：`dict.pop(key)` 弹出key的value, key不能为空\n",
    "- `popitem`： 随机弹键值对，通常弹尾巴"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# delete key  del dict[key]\n",
    "del a['stu_id']\n",
    "a\n",
    "# del a #删除整个dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{}"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a.clear()\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['june', 'may', 'april']\n",
      "{'age': [21, 22, 33], 'sex': 'female', 'phone': '1234'}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "('phone', '1234')"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# dict.pop(key)\n",
    "a = {'name':['june','may','april'],'age':[21,22,33],'sex':'female','phone':'1234'}\n",
    "print(a.pop('name'))  # pop()内不能为空\n",
    "print(a)\n",
    "# dict.popitem()   #随机弹，一般从尾巴弹出\n",
    "a.popitem()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 键值对个数\n",
    "- `len(dict)`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 91,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = {'name':['june','may','april'],'age':[21,22,33],'sex':'female','phone':'1234'}\n",
    "len(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 查找\n",
    "\n",
    "- `dict.keys()`\n",
    "- `dict.values()`\n",
    "- `dict.items()`: 返回键值对，（键，值）\n",
    "- `dict.get()`: 获取键所对应的数值，如果没有key,不会报错"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "dict_keys(['name', 'age', 'sex', 'phone'])\n",
      "['name', 'age', 'sex', 'phone']\n",
      "dict_values([['june', 'may', 'april'], [21, 22, 33], 'female', '1234'])\n",
      "dict_items([('name', ['june', 'may', 'april']), ('age', [21, 22, 33]), ('sex', 'female'), ('phone', '1234')])\n"
     ]
    }
   ],
   "source": [
    "# dict.keys()\n",
    "print(a.keys())\n",
    "print(list(a.keys()))\n",
    "# dict.values()\n",
    "print(a.values())\n",
    "# dict.items() \n",
    "print(a.items())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n",
      "['june', 'may', 'april']\n",
      "{'name': ['june', 'may', 'april'], 'age': [21, 22, 33], 'sex': 'female', 'phone': '1234'}\n"
     ]
    }
   ],
   "source": [
    "# dict.get(key) 获取键所对应的数值，如果没有key,不会报错\n",
    "a = {'name':['june','may','april'],'age':[21,22,33],'sex':'female','phone':'1234'}\n",
    "print(a.get('hey'))\n",
    "# dict.get(key,1) 如果没有key,则会新建一个，赋值为后面的数，并返回该值,dict本身不做修改\n",
    "print(a.get('name','you'))  # 如果key存在，在不理会后面的变量\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 练习：计算词频\n",
    "sen = 'My father was a self-taught mandolin player. He was one of the best string instrument players in our town. He could not read music, but if he heard a tune a few times, he could play it. When he was younger, he was a member of a small country music'\n",
    "word_count = {}\n",
    "# first try\n",
    "# for words in sen:\n",
    "#     # BAD CODING!\n",
    "#     word_count[words] = word_count.get(words,0) + 1\n",
    "# word_count\n",
    "\n",
    "# 2nd try\n",
    "# for words in sen.split():\n",
    "#     # improved, still more to be done\n",
    "#     word_count[words] = word_count.get(words,0) + 1\n",
    "# word_count\n",
    "\n",
    "# 3rd try\n",
    "for words in sen.replace('.','').split():\n",
    "    word_count[words] = word_count.get(words,0) + 1\n",
    "word_count"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `OrderedDict`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 153,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OrderedDict([('m0', '123'), ('m1', '345')])\n"
     ]
    }
   ],
   "source": [
    "# OrderedDict\n",
    "from collections import OrderedDict\n",
    "\n",
    "a=OrderedDict()\n",
    "a['m0']='123'\n",
    "a['m1']='345'\n",
    "print(a)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### list 转化为 dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 'b', 'c': 'd'}\n"
     ]
    }
   ],
   "source": [
    "#类型之间可以相互转换  list ---dict\n",
    "\n",
    "a=[('a','b'),('c','d')]\n",
    "b=dict(a)\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('a', 'b'), ('c', 'd')]"
      ]
     },
     "execution_count": 101,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(b.items())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 数据类型转换，只需将数据类型作为函数名称即可。\n",
    "\n",
    "> repr() 将对象x转换为表达式字符串\n",
    "\n",
    "> eval() 计算在字符串中的有效python表达式，并返回一个对象\n",
    "\n",
    "> frozenset() 转换为不可变集合\n",
    "\n",
    "> chr()  将一个整数转换为字符\n",
    "\n",
    "> unichr(x) 将一个整数转换为unicode字符\n",
    "\n",
    "> ord() 将字符转换为它的整数值\n",
    "\n",
    "> hex(x)  : 16进制\n",
    "\n",
    "> oct(x)  ：8进制\n",
    "\n",
    "> bin(x) : 2进制"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "20"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "eval('2*10')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "97"
      ]
     },
     "execution_count": 93,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ord('a')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
